package com.example.research.controller;

import com.example.research.dto.ApiResponse;
import com.example.research.entity.HorizontalProject;
import com.example.research.service.AuthService;
import com.example.research.service.HorizontalProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDate;
import java.util.List;

/**
 * 横向课题控制器
 */
@RestController
@RequestMapping("/horizontal-projects")
@Validated
public class HorizontalProjectController {

    @Autowired
    private HorizontalProjectService horizontalProjectService;

    @Autowired
    private AuthService authService;

    /**
     * 获取当前用户ID
     */
    private Long getCurrentUserId(String authHeader) {
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            throw new RuntimeException("未提供有效的认证信息");
        }
        String token = authHeader.substring(7);
        return authService.getUserIdFromToken(token);
    }

    /**
     * 查询所有横向课题
     */
    @GetMapping
    public ApiResponse<List<HorizontalProject>> getAllProjects() {
        try {
            List<HorizontalProject> projects = horizontalProjectService.findAll();
            return ApiResponse.success(projects);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 根据ID查询横向课题
     */
    @GetMapping("/{id}")
    public ApiResponse<HorizontalProject> getProjectById(@PathVariable Long id) {
        try {
            HorizontalProject project = horizontalProjectService.findById(id);
            if (project == null) {
                return ApiResponse.notFound("横向课题不存在");
            }
            return ApiResponse.success(project);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 查询当前用户的横向课题
     */
    @GetMapping("/my")
    public ApiResponse<List<HorizontalProject>> getMyProjects(@RequestHeader("Authorization") String authHeader) {
        try {
            Long userId = getCurrentUserId(authHeader);
            List<HorizontalProject> projects = horizontalProjectService.findByUserId(userId);
            return ApiResponse.success(projects);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 根据审核状态查询横向课题
     */
    @GetMapping("/audit-status/{status}")
    public ApiResponse<List<HorizontalProject>> getProjectsByAuditStatus(@PathVariable Integer status) {
        try {
            List<HorizontalProject> projects = horizontalProjectService.findByAuditStatus(status);
            return ApiResponse.success(projects);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 根据甲方单位查询横向课题
     */
    @GetMapping("/party/{partyName}")
    public ApiResponse<List<HorizontalProject>> getProjectsByPartyName(@PathVariable String partyName) {
        try {
            List<HorizontalProject> projects = horizontalProjectService.findByPartyName(partyName);
            return ApiResponse.success(projects);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 根据条件查询横向课题
     */
    @GetMapping("/search")
    public ApiResponse<List<HorizontalProject>> searchProjects(
            @RequestParam(required = false) Long userId,
            @RequestParam(required = false) String partyName,
            @RequestParam(required = false) Integer auditStatus,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
        try {
            List<HorizontalProject> projects = horizontalProjectService.findByConditions(
                    userId, partyName, auditStatus, startDate, endDate);
            return ApiResponse.success(projects);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 创建横向课题
     */
    @PostMapping
    public ApiResponse<HorizontalProject> createProject(@Valid @RequestBody HorizontalProject project,
                                                       @RequestHeader("Authorization") String authHeader) {
        try {
            Long userId = getCurrentUserId(authHeader);
            project.setUserId(userId);
            HorizontalProject createdProject = horizontalProjectService.createProject(project);
            return ApiResponse.success("横向课题创建成功", createdProject);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 更新横向课题
     */
    @PutMapping("/{id}")
    public ApiResponse<HorizontalProject> updateProject(@PathVariable Long id,
                                                       @Valid @RequestBody HorizontalProject project,
                                                       @RequestHeader("Authorization") String authHeader) {
        try {
            Long userId = getCurrentUserId(authHeader);
            project.setId(id);
            project.setUserId(userId);
            HorizontalProject updatedProject = horizontalProjectService.updateProject(project);
            return ApiResponse.success("横向课题更新成功", updatedProject);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 删除横向课题
     */
    @DeleteMapping("/{id}")
    public ApiResponse<String> deleteProject(@PathVariable Long id,
                                           @RequestHeader("Authorization") String authHeader) {
        try {
            Long userId = getCurrentUserId(authHeader);
            horizontalProjectService.deleteProject(id, userId);
            return ApiResponse.success("横向课题删除成功");
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 提交审核
     */
    @PostMapping("/{id}/submit")
    public ApiResponse<String> submitForAudit(@PathVariable Long id,
                                            @RequestHeader("Authorization") String authHeader) {
        try {
            Long userId = getCurrentUserId(authHeader);
            horizontalProjectService.submitForAudit(id, userId);
            return ApiResponse.success("横向课题提交审核成功");
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
}
